<route lang="json5">
{
  needLogin: true,
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '学习任务',
  },
}
</route>

<template>
  <view class="course-main">
    <!-- 筛选条件 -->
    <!-- <view class="filter-bar flex items-center m-b-24rpx h-54rpx m-l-10rpx">
      <div>
        <text class="text-30rpx color-#3D3D3D font-bold">状态</text>
      </div>
      <div class="h-full m-l-15rpx">
        <wd-drop-menu>
          <wd-drop-menu-item v-model="taskStatus" :options="taskStatusOptions" />
        </wd-drop-menu>
      </div>
      <div class="ml-20rpx">
        <text class="text-30rpx color-#3D3D3D font-bold">截止时间</text>
      </div>
      <div class="ml-20rpx bg-white py-9rpx px-30rpx" @click="openCalendar">
        <text class="text-30rpx color-#999999">{{ formatValue }}</text>
        <wd-icon class="ml-4rpx" name="calendar" size="28rpx" />
      </div>
    </view> -->
    <!-- 顶部导航栏 -->
   <wd-navbar
      safeAreaInsetTop
      left-arrow
      title="学习任务"
      @click-left="handleClickLeft"
    ></wd-navbar>
    <!-- 任务列表 -->
    <scroll-view scroll-y class="task-list">
      <view v-if="taskList.length > 0">
        <view
          v-for="(task, index) in taskList"
          :key="index"
          class="task-item px-24rpx"
          @click="handleTaskClick(task)"
        >
          <view @click.stop="closeOutside">
            <wd-swipe-action>
              <view
                class="flex items-center p-20rpx bg-white rounded-8rpx mb-20rpx h-80rpx"
                @click="viewTaskDetail(task)"
              >
                <wd-img v-if="`${task.status}` === '0'" :src="taskStatus0Png" size="60rpx" />
                <wd-img v-if="`${task.status}` === '1'" :src="taskStatus1Png" size="60rpx" />
                <wd-img v-if="`${task.status}` === '2'" :src="taskStatus2Png" size="60rpx" />
                <view class="flex-1 ml-20rpx">
                  <view class="text-24rpx text-[#3D3D3D] font-bold mb-15rpx">
                    {{ task.taskName }}
                  </view>
                  <view class="text-20rpx text-[#999999]">
                    截止完成时间：{{ dateFormat(task.deadline) }}
                  </view>
                </view>
                <wd-tag
                  :bg-color="getTagType(task.status, 'bg')"
                  :color="getTagType(task.status, 'color')"
                >
                  {{ getTaskStatus(task.status) }}
                </wd-tag>
              </view>
              <template #right>
                <view v-if="task.status == 0" class="action">
                  <view class="button" @click="handleAction(task.taskId)">开启</view>
                </view>
              </template>
            </wd-swipe-action>
          </view>
          <view v-if="taskList.length === 0" class="empty-tip text-center py-30px color-#999">
            暂无任务
          </view>
        </view>
        <!-- 添加加载状态和加载完成的提示 -->
        <wd-loadmore
          :state="state"
          @reload="loadMore"
          finished-text="已经全部加载完毕"
        ></wd-loadmore>
      </view>
      <view v-else class="empty-state flex-center flex-col mt-200rpx">
        <wd-status-tip :image="emptyImage" tip="暂无数据" />
      </view>
    </scroll-view>
    <!-- 新增任务 -->
    <wd-button class="add-task-btn" @click="handleAddTask">新增任务</wd-button>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { dayjs, useToast, useQueue } from 'wot-design-uni'
import { CalendarInstance } from 'wot-design-uni/components/wd-calendar/types'
/* 引入 图片 */
import taskStatus2Png from '@/static/images/course/task/task-status-1.png'
import taskStatus1Png from '@/static/images/course/task/task-status-2.png'
import taskStatus0Png from '@/static/images/course/task/task-status-3.png'
/* 引入 暂无数据 - 图片 */
import emptyImage from '@/static/images/icons/empty.png'
/* 引入 接口 */
import { getTaskListApi, updateStatusApi } from '@/service/edu/task/index'

const calendar = ref<CalendarInstance>()
// 搜索相关
const value = ref<number>(Date.now())
const formatValue = ref<string>(dayjs(Date.now()).format('YYYY-MM-DD'))

const { closeOutside } = useQueue()

const toast = useToast()

async function handleAction(taskId) {
  try {
    await updateStatusApi({ taskId })
  } catch (e) {
    console.error(e)
  } finally {
    getTaskList(false)
  }
}

const state = ref<'loading' | 'finished' | 'error'>('loading')
const loading = ref(false)
const finished = ref(false)
/* 定义 列表数组(后台返回) */
const taskList = ref<any[]>([])
/* 定义 分页配置 */
const pageNum = ref(1)
const pageSize = ref(10)

/* 课程id和课程名称 */
const courseId = ref('')
const courseName = ref('')

/* 获取任务列表 */
async function getTaskList(isLoadMore = false) {
  if (loading.value || (finished.value && isLoadMore)) return
  try {
    loading.value = true
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      courseId: courseId.value,
    }

    /* 判断调取哪个接口 */
    const data: any = await getTaskListApi(params)
    if (data?.code === 200) {
      const { rows = [], total = 0 } = data || {}

      if (isLoadMore) {
        taskList.value = [...taskList.value, ...rows]
      } else {
        taskList.value = rows
      }

      // 判断是否加载完所有数据
      finished.value = taskList.value.length >= total
      state.value = finished.value ? 'finished' : 'loading'
    }
  } catch (error) {
    console.error('获取我的任务列表失败:', error)
    state.value = 'error'
  } finally {
    loading.value = false
  }
}

/* 截至时间格式化 */
function dateFormat(str) {
  if (!str || !str.includes('-')) return ''
  const parts = str.split('-')
  const year = parts[0]
  const month = parts[1].padStart(2, '0')
  const day = parts[2].padStart(2, '0')
  return `${year}-${month}-${day}`
}

/* 加载更多数据 */
const loadMore = async () => {
  if (!loading.value && !finished.value) {
    pageNum.value++
    await getTaskList(true)
  }
}

/* 监听页面滚动到底部 */
onReachBottom(() => {
  if (!loading.value && !finished.value) {
    loadMore()
  }
})

/* 顶部导航栏 - 返回 */
function handleClickLeft() {
  // uni.navigateTo({
  //   url: `/pages/course/detail?id=${courseId.value}`,
  // })
  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack()
  } else {
    uni.redirectTo({
      url: '/pages/course/detail',
    })
  }
}

/* 页面加载时获取数据 */
onLoad(async (query) => {
  courseId.value = query.courseId || ''
  courseName.value = query.courseName || ''
  await getTaskList(false)
})

// 任务状态筛选
const taskStatus = ref('all')
const taskStatusOptions = [
  { value: 'all', label: '全部作业' },
  { value: 'pending', label: '待完成' },
  { value: 'reviewing', label: '批改中' },
  { value: 'completed', label: '已完成' },
  { value: 'closed', label: '已关闭' },
]

const getTaskStatus = (status: string) => {
  const statusMap: Record<string, string> = {
    0: '未开启',
    1: '已开启',
    2: '已关闭',
  }
  return statusMap[status]
}

const getTagType = (status: string, type) => {
  if (!status) return ''
  const typeMap = {
    0: { bg: '#CBCFFF', color: '#515FFE' },
    1: { bg: '#E3EEFF', color: '#458AFE' },
    2: { bg: '#FEE2E4', color: '#F73A4A' },
  }
  if (type === 'bg') {
    return typeMap[status].bg
  } else {
    return typeMap[status].color
  }
}
const viewTaskDetail = (task: any) => {
  uni.navigateTo({
    url: `/pages/task/detail?courseId=${courseId.value}&courseName=${courseName.value}&taskId=${task.taskId}`,
  })
}

// 处理任务点击
const handleTaskClick = (task: any) => {
  uni.navigateTo({
    url: `/pages/task/detail?id=${task.id}`,
  })
}

/* 新增任务 */
function handleAddTask() {
  uni.navigateTo({
    url: `/pages/task/add?courseId=${courseId.value}&courseName=${courseName.value}`,
  })
}
</script>

<style lang="scss" scoped>
.task-list {
  height: calc(100vh - 246rpx);
  margin-top: 30rpx;
  overflow-y: auto;
}
:deep(.wd-drop-menu__item-title::after) {
  bottom: 0px !important;
}
.course-main {
  height: 100vh;
  background-color: #f2f2f6;
}
.action {
  height: 100%;

  .button {
    display: flex;
    align-items: center;
    height: 100%;
    padding: 0 40rpx;
    font-size: 20rpx !important;
    color: white;
    background-color: #00cc7e;
  }
}

:deep(.wd-tag) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80rpx;
  height: 40rpx;
  font-weight: 700;
}
/* 新增任务 */
:deep(.add-task-btn) {
  position: fixed;
  bottom: 50rpx;
  left: 50%;
  display: block;
  width: 90%;
  height: 86rpx !important;
  background: linear-gradient(90deg, #20a4ff 2%, #0d53ff 100%) !important;
  transform: translateX(-50%);
}
</style>
